<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
//require_once '../vendor/autoload.php';
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Products;
use App\Models\Users;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Log;
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
use PayPal\Api\PaymentExecution;

class PayController extends BaseController
{
    private $_api_context;
    const accept_url='https://oceanstar.bscd8.com/api/notify';


    public function __construct()

    {

        $payPal_config = config('pyment.paypal');

        // 初始化 PayPal Api context

        $this->_api_context = new ApiContext(new OAuthTokenCredential(

            $payPal_config['client_id'],

            $payPal_config['secret']

        ));

        $this->_api_context->setConfig($payPal_config['settings']);
    }

    /**
     * 发起支付
     */
    // public function index(Request $request)
    // {


    //    $order_id=$request->input('order_id');
    //    if(!$order_id) return $this->apiError('訂單id不能為空');
    //   $order= Order::where('id',$order_id)->first();
    //   if(!$order||$order->status>10) return $this->apiError('訂單異常');


    //     $product =$order->product_item['name'];
    //     $price = $order->pay_price;
    //     $shipping = 0;
    //     $description = $order->product_item['name'];
    //     $paypal = $this->_api_context;
    //     $total = $price ;//总价
    //     // $address= $order->address['address'].$order->address['address_detail'];
    //     // dd($address);
    //     $payer = new Payer();
    //     $payer->setPaymentMethod('paypal');

    //     $item = new Item();
    //     $item->setName($product)->setCurrency('HKD')->setQuantity(1)->setPrice($price);

    //     $itemList = new ItemList();
    //     $itemList->setItems([$item]);

    //     // $itemList->setShippingAddress($address);

    //     $details = new Details();
    //     $details->setShipping($shipping)->setSubtotal($price);

    //     $amount = new Amount();
    //     $amount->setCurrency('HKD')->setTotal($total)->setDetails($details);

    //     $transaction = new Transaction();
    //     $transaction->setAmount($amount)->setItemList($itemList)->setDescription($description)->setInvoiceNumber(uniqid());

    //     $redirectUrls = new RedirectUrls();
    //     $redirectUrls->setReturnUrl(self::accept_url . "?success=true&order_id=$order->id")->setCancelUrl(self::accept_url . '/?success=false');

    //     $payment = new Payment();
    //     $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);


    //     try {
    //         $payment->create($paypal);
    //     } catch (PayPalConnectionException $e) {
    //        return $this->apiError($e->getData()) ;
    //         die();
    //     }
    //     $approvalUrl = $payment->getApprovalLink();

    //     // header("Location: {$approvalUrl}");
    //     return $this->success($approvalUrl);
    //     // dd($_SERVER['APP_URL']);
    // }


    // /**
    //  * 发起支付
    //  */
    public function index(Request $request)
    {

        $order_id=$request->input('order_id');
        $payType=$request->input('payType');
        if(empty($payType)) return $this->apiError('支付类型不能为空');

        if(!$order_id) return $this->apiError('訂單id不能為空');
       $order= Order::where('id',$order_id)->where('users_id',$request->userId)->first();
       if(!$order||$order->status>10){
           return $this->apiError('訂單異常');
       }

        /**
         * paytype=1 钱包支付
         */
        DB::beginTransaction();


            if($payType==1){

                $wallet=Users::where('id',$request->userId)->value('wallet');

                if(empty($wallet)||($wallet-$order->pay_price<0)) return $this->apiError('钱包余额不足');

               $a= Users::where('id',$request->userId)->decrement('wallet',$order->pay_price);


                if(!Order::where('id',$order_id)->where('users_id',$request->userId)->update(['status'=>20,'pay_mode'=>2])){
                    DB::rollBack();
                }
                if(!empty($order->product_item)){
                    $res= DB::table('products')->whereIn('id',array_column($order->product_item,'id'))->get()->toArray();
                }
                if(!empty($res)){
                    foreach ($res as $item){
                        DB::table('users')->where('id',$order->users_id)->increment('integrate',$item['integral']);
                        DB::table('users')->where('id',$order->users_id)->increment('integrate_ing',$item['integral']);
                    }
                }
                DB::commit();
                return $this->success();
            }else {



                $product = $order->product_item[0]['name']??'预约';
                $price = $order->pay_price??0;
                $shipping = 0;
                $description = $order->product_item[0]['name']??'预约';


                $paypal = $this->_api_context;
                $total = $price;//总价
                $address='香港';
//                $address = $order->address['address'];

                // $product = '1123';
                // $price = 1;
                // $shipping = 0;
                // $description = '1123123';
                // $paypal = $this->_api_context;
                // $total = $price + $shipping;//总价

                $payer = new Payer();
                $payer->setPaymentMethod('paypal');

                $item = new Item();
                $item->setName($product)->setCurrency('HKD')->setQuantity(1)->setPrice($price);

                $itemList = new ItemList();
                $itemList->setItems([$item]);

                $details = new Details();
                $details->setShipping($shipping)->setSubtotal($price);

                $amount = new Amount();
                $amount->setCurrency('HKD')->setTotal($total)->setDetails($details);

                $transaction = new Transaction();
                $transaction->setAmount($amount)->setItemList($itemList)->setDescription($description)->setInvoiceNumber(uniqid());

                $redirectUrls = new RedirectUrls();
                // $redirectUrls->setReturnUrl(self::accept_url . '?success=true')->setCancelUrl(self::accept_url . '/?success=false');
                $redirectUrls->setReturnUrl(self::accept_url . "?success=true&order_id=$order->id")->setCancelUrl(self::accept_url . '/?success=false');

                $payment = new Payment();
                $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);

                try {
                    $payment->create($paypal);
                } catch (PayPalConnectionException $e) {
                    echo $e->getData();
                    die();
                }

                $approvalUrl = $payment->getApprovalLink();
                return $this->success($approvalUrl);
                header("Location: {$approvalUrl}");
            }


    }

    /**
     * 錢包充值
     */
    public function burse(Request $request)
    {
        $money=$request->input('money');

        $user=$request->userId;
        if(empty($money) || ($money<500)) return $this->apiError('充值金額不得低於500');
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item = new Item();
        $item->setName('Coins')->setCurrency('HKD')->setQuantity(1)->setPrice($money);

        $itemList = new ItemList();
        $itemList->setItems([$item]);


        $details = new Details();
        $details->setShipping(0)->setSubtotal($money);

        $amount = new Amount();
        $amount->setCurrency('HKD')->setTotal($money)->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)->setItemList($itemList)->setDescription('Coins')->setInvoiceNumber(uniqid());

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl(self::accept_url . "?success=true&user_id=$user&money=$money")->setCancelUrl(self::accept_url . '/?success=false');

        $payment = new Payment();
        $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);


        try {
            $payment->create($this->_api_context);
        } catch (PayPalConnectionException $e) {
           return $this->apiError($e->getData()) ;
            die();
        }
        $approvalUrl = $payment->getApprovalLink();

        // header("Location: {$approvalUrl}");
        return $this->success($approvalUrl);
        // dd($_SERVER['APP_URL']);

    }




    /**
     * 支付回调
     */
    public function notify(Request $request)
    {

        $params=$request->all();
        $success = trim($params['success']);
        if ($success == 'false' && !isset($params['paymentId']) && !isset($params['PayerID'])) {
            Log::error('取消付款') ;die;
        }
        $paymentId = trim($params['paymentId']);
        $PayerID = trim($params['PayerID']);
        if (!isset($success, $paymentId, $PayerID)) {
            Log::error('支付失败') ;die;
        }
        if ((bool)$params['success'] === 'false') {
            Log::error(  '支付失败，支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');die;
        }
        $payment = Payment::get($paymentId, $this->_api_context);
        $execute = new PaymentExecution();
        $execute->setPayerId($PayerID);
        try {
            $payment->execute($execute, $this->_api_context);
        } catch (Exception $e) {
            Log::error(  '支付失败，支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');die;
        }

        if(!empty($request->input('order_id'))){

          $status=  $this->updateOrder($params['order_id'],1);
        }else{
            $status= $this->updateOrder(null,1,$params['user_id'],$params['money']);
        }

         if($status)   return view('paymentSuccess');;
         return view('paymentError');
    }



    /**
     * 修改订单or 用户钱包
     */
    protected function updateOrder($order_id=null,$pay_type,$user=null,$money=0)
    {
      if(!empty($order_id)){
          //注意
        $order=Order::find($order_id);

        // array_walk($order['product_item'],function($item){
        //     Products::where('id',$item['id'])->decrement('num',$item['count']);
        // });

        $res=  Order::where('id',$order_id)->update([
            'status'=>20
        ]);

          if(!empty($order->product_item)){
              $res= DB::table('products')->whereIn('id',array_column($order->product_item,'id'))->get()->toArray();
              foreach ($res as $item){

                  DB::table('users')->where('id',$order->users_id)->increment('integrate_ing',$item->integral);
                  DB::table('users')->where('id',$order->users_id)->increment('integrate',$item->integral);
              }
          }


        if($res) return $this->success();
        Log::error("订单状态修改失败".$order_id);
        return $this->apiError('訂單狀態修改失敗');
      }else{
       $user= Users::where('id',$user)->increment('wallet',$money);

        if($user) return true;
       Log::error("钱包充值失败".$user);
        return false;
      }

    }
}
